const path = require('path');
const express = require('express');
const http = require('http');
const { WebSocketServer } = require('ws');
const { v4: uuidv4 } = require('uuid');

const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server });

const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';

// 静态资源
app.use(express.static(path.join(__dirname, 'public')));

// 连接的客户端集合
const clients = new Map(); // ws -> { id, name }

function broadcast(data, exceptWs = null) {
	const message = JSON.stringify(data);
	for (const [ws] of clients) {
		if (ws.readyState === ws.OPEN && ws !== exceptWs) {
			ws.send(message);
		}
	}
}

wss.on('connection', (ws) => {
	const user = { id: uuidv4(), name: `用户${String(clients.size + 1).padStart(2, '0')}` };
	clients.set(ws, user);

	// 通知新用户加入
	broadcast({ type: 'system', text: `${user.name} 加入了聊天室`, online: Array.from(clients.values()) });

	ws.on('message', (raw) => {
		let payload;
		try {
			payload = JSON.parse(raw);
		} catch (e) {
			return;
		}

		if (payload.type === 'chat') {
			broadcast({ type: 'chat', from: user, text: String(payload.text || '').slice(0, 1000), ts: Date.now() });
		}
	});

	ws.on('close', () => {
		clients.delete(ws);
		broadcast({ type: 'system', text: `${user.name} 离开了聊天室`, online: Array.from(clients.values()) });
	});

	ws.send(JSON.stringify({ type: 'welcome', self: user, online: Array.from(clients.values()) }));
});

server.listen(PORT, HOST, () => {
	const nets = require('os').networkInterfaces();
	const addrs = [];
	for (const name of Object.keys(nets)) {
		for (const net of nets[name] || []) {
			if (net.family === 'IPv4' && !net.internal) addrs.push(net.address);
		}
	}
	console.log('Server listening on:');
	console.log(`- http://localhost:${PORT}`);
	addrs.forEach(ip => console.log(`- http://${ip}:${PORT}`));
});
